package com.gxc.binarySearch;

/**
 * 在排序数组中查找元素的第一个和最后一个位置
 * 给你一个按照非递减顺序排列的整数数组 nums，和一个目标值 target。请你找出给定目标值在数组中的开始位置和结束位置。
 *
 * 如果数组中不存在目标值 target，返回 [-1, -1]。
 *
 * 你必须设计并实现时间复杂度为 O(log n) 的算法解决此问题
 */
public class SearchRange {

    public static void main(String[] args) {
        int[] ints = searchRange(new int[]{5, 7, 7, 8, 8, 10}, 8);
        System.out.println("");
    }

    public static int[] searchRange(int[] nums, int target) {
        int[] res = new int[]{-1,-1};
        int mid = 0, left = 0, right = nums.length - 1;
        while (left<=right) {
            mid = (left + right)/2;
            if (nums[mid]<target) {
                left=mid + 1;
            } else if (nums[mid] > target){
                right = mid-1;
            } else {
                res[0] = mid;
                right = mid -1;
            }
        }

        left = right==-1 ?0:right;
        right = nums.length-1;
        while (left<=right) {
            mid = (left + right)/2;
            if (nums[mid]<target) {
                left=mid + 1;
            } else if (nums[mid] > target){
                right = mid-1;
            } else {
                res[1] = mid;
                left = mid+1;
            }
        }

        return res;
    }
}
